﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace GMap.NET.EXT
{
    public class PointLatLngs
    {
        public static PointLatLngs at(List<PointLatLng> points)
        {
            PointLatLngs pointLatLngs = new PointLatLngs
            {
                points = points
            };
            return pointLatLngs;
        }

        public static PointLatLngs parse(string coordinates, string pointSeparator, string latlngSerpartor)
        {
            List<PointLatLng> points = PointLatLngs.parseCoordinates(coordinates, pointSeparator, latlngSerpartor);
            return PointLatLngs.at(points);
        }

        private List<PointLatLng> points = null;

        private PointLatLngs()
        {
        }

        public List<PointLatLng> Points
        {
            get { return points; }
        }

        public RectLatLng Region
        {
            get { return calcuteRegion(points); }
        }

        public PointLatLng Center
        {
            get { return caculateCenter(points); }
        }
        
        public double Distance
        {
            get { return caculateDistance(points, false); }
        }

        public double DistanceSeal
        {
            get { return caculateDistance(points, true); }
        }

        public PointLatLng First
        {
            get { return Valid ? points.First() : PointLatLng.Empty; }
        }

        public PointLatLng Last
        {
            get { return Valid ? points.Last() : PointLatLng.Empty; }
        }

        public bool Valid
        {
            get { return points.Count > 0; }
        }

        public PointLatLng getPositionByDistance(double distance)
        {
            return PointLatLngs.calculatePosition(points, distance);
        }

        public void Reverse()
        {
            this.points.Reverse();
        }

        #region GPS_UTILS

        private const double earth_Radius = 6378.137;//地球半径
        private static double Radius(double d)
        {
            return d * Math.PI / 180.0;
        }

        public static RectLatLng calcuteRegion(List<PointLatLng> points)
        {
            if (points.Count == 0)
            {
                return RectLatLng.Empty;
            }

            double minLat = double.MaxValue, maxLat = double.MinValue, minLng = double.MaxValue, maxLng = double.MinValue;

            foreach (PointLatLng p in points)
            {
                if (p.Lat < minLat) minLat = p.Lat;
                if (p.Lat > maxLat) maxLat = p.Lat;
                if (p.Lng < minLng) minLng = p.Lng;
                if (p.Lng > maxLng) maxLng = p.Lng;
            }

            return RectLatLng.FromLTRB(minLng, maxLat, maxLng, minLat);

        }

        public static PointLatLng caculateCenter(List<PointLatLng> points)
        {
            RectLatLng region = calcuteRegion(points);
            if (region.IsEmpty) return PointLatLng.Empty;

            double lng = (region.Left + region.Right) / 2;
            double lat = (region.Top + region.Bottom) / 2;
            return new PointLatLng(lat, lng);

        }

        public static List<PointLatLng> parseCoordinates(string coordinates, string pointSeparator, string latlngSerpartor)
        {
            List<PointLatLng> points = new List<PointLatLng>();

            try
            {
                string[] splits = coordinates.Split(pointSeparator.ToCharArray());
                foreach (string s in splits)
                {
                    try
                    {
                        string[] x = s.Split(latlngSerpartor.ToCharArray());
                        if (x.Length >= 2)
                        {
                            double lat = double.Parse(x[1]);
                            double lng = double.Parse(x[0]);
                            PointLatLng latLng = new PointLatLng(lat, lng);
                            points.Add(latLng);
                        }
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e.Message);
                    }

                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }

            return points;
        }



        /// <summary>
        /// 两点间距离
        /// </summary>
        /// <param name="lat1"></param>
        /// <param name="lng1"></param>
        /// <param name="lat2"></param>
        /// <param name="lng2"></param>
        /// <returns></returns>
        public static double caculateDistance(double lat1, double lng1, double lat2, double lng2)
        {
            double radLat1 = Radius(lat1);
            double radLat2 = Radius(lat2);
            double a = radLat1 - radLat2;
            double b = Radius(lng1) - Radius(lng2);

            double s = 2 * Math.Asin(Math.Sqrt(Math.Pow(Math.Sin(a / 2), 2) +
             Math.Cos(radLat1) * Math.Cos(radLat2) * Math.Pow(Math.Sin(b / 2), 2)));
            s = s * earth_Radius;
            s = Math.Round(s * 10000) / 10000;
            return s;
        }

        public static double caculateDistance(PointLatLng p1, PointLatLng p2)
        {
            if(p1.IsEmpty || p2.IsEmpty)
            {
                return 0;
            }
            else
            {
                return caculateDistance(p1.Lat, p1.Lng, p2.Lat, p2.Lng);
            }
        }

        public static double caculateDistance(List<PointLatLng> points, bool seal)
        {
            double distance = 0.0;

            PointLatLng current = PointLatLng.Empty;

            points.ForEach((p) =>
            {
                distance += caculateDistance(current, p);
                current = p;
            });

            if(seal && points.Count > 1)
            {
                distance += caculateDistance(points.First(), points.Last());
            }

            return distance;

        }

        private static PointLatLng calculatePosition(List<PointLatLng> points, double distance)
        {

            PointLatLng current = PointLatLng.Empty;

            foreach (PointLatLng p in points)
            {
                if (current != PointLatLng.Empty && p != PointLatLng.Empty)
                {
                    double dis = caculateDistance(current, p);
                    if (distance > dis)
                    {
                        distance -= dis;
                    }
                    else
                    {
                        double ratio = distance / dis;

                        double lat = (p.Lat - current.Lat) * ratio + current.Lat;
                        double lng = (p.Lng - current.Lng) * ratio + current.Lng;

                        return new PointLatLng(lat, lng);

                    }
                }
                current = p;
            }

            return PointLatLng.Empty;

        }

        #endregion


    }

    class EvilTransform
    {
        const double pi = 3.14159265358979324;

        //
        // Krasovsky 1940
        //
        // a = 6378245.0, 1/f = 298.3
        // b = a * (1 - f)
        // ee = (a^2 - b^2) / a^2;
        const double a = 6378245.0;
        const double ee = 0.00669342162296594323;

        public static PointLatLng transform(PointLatLng wgLatLng)
        {
            transform(wgLatLng.Lat, wgLatLng.Lng, out double mgLat, out double mgLon);
            var mgLatLng = new PointLatLng
            {
                Lat = mgLat,
                Lng = mgLon
            };
            return mgLatLng;
        }

        //
        // World Geodetic System ==> Mars Geodetic System
        public static void transform(double wgLat, double wgLon, out double mgLat, out double mgLon)
        {
            if (outOfChina(wgLat, wgLon))
            {
                mgLat = wgLat;
                mgLon = wgLon;
                return;
            }
            double dLat = transformLat(wgLon - 105.0, wgLat - 35.0);
            double dLon = transformLon(wgLon - 105.0, wgLat - 35.0);
            double radLat = wgLat / 180.0 * pi;
            double magic = Math.Sin(radLat);
            magic = 1 - ee * magic * magic;
            double sqrtMagic = Math.Sqrt(magic);
            dLat = (dLat * 180.0) / ((a * (1 - ee)) / (magic * sqrtMagic) * pi);
            dLon = (dLon * 180.0) / (a / sqrtMagic * Math.Cos(radLat) * pi);
            mgLat = wgLat + dLat;
            mgLon = wgLon + dLon;
        }

        static bool outOfChina(double lat, double lon)
        {
            if (lon < 72.004 || lon > 137.8347)
                return true;
            if (lat < 0.8293 || lat > 55.8271)
                return true;
            return false;
        }

        static double transformLat(double x, double y)
        {
            double ret = -100.0 + 2.0 * x + 3.0 * y + 0.2 * y * y + 0.1 * x * y + 0.2 * Math.Sqrt(Math.Abs(x));
            ret += (20.0 * Math.Sin(6.0 * x * pi) + 20.0 * Math.Sin(2.0 * x * pi)) * 2.0 / 3.0;
            ret += (20.0 * Math.Sin(y * pi) + 40.0 * Math.Sin(y / 3.0 * pi)) * 2.0 / 3.0;
            ret += (160.0 * Math.Sin(y / 12.0 * pi) + 320 * Math.Sin(y * pi / 30.0)) * 2.0 / 3.0;
            return ret;
        }

        static double transformLon(double x, double y)
        {
            double ret = 300.0 + x + 2.0 * y + 0.1 * x * x + 0.1 * x * y + 0.1 * Math.Sqrt(Math.Abs(x));
            ret += (20.0 * Math.Sin(6.0 * x * pi) + 20.0 * Math.Sin(2.0 * x * pi)) * 2.0 / 3.0;
            ret += (20.0 * Math.Sin(x * pi) + 40.0 * Math.Sin(x / 3.0 * pi)) * 2.0 / 3.0;
            ret += (150.0 * Math.Sin(x / 12.0 * pi) + 300.0 * Math.Sin(x / 30.0 * pi)) * 2.0 / 3.0;
            return ret;
        }
    }

}
